package main

import (
    "bufio"
    "context"
    "fmt"
    "gitee.com/gober/prototest/proto"
    "google.golang.org/grpc"
    "os"

    //"os"
    "time"
)

const address = "localhost:6666"

func main() {
    fmt.Println("启动客户端。。。")
    // 建立连接
    conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
    fmt.Println("客户端连接服务器成功！")
    if err != nil {
        fmt.Printf("Client Dial error : %s\r\n", err.Error())
    }
    defer conn.Close()

    cli1 := proto.NewMessageServiceClient(conn)
    ////ctx, cancle := context.WithTimeout(context.Background(), 3*time.Second)
    //ctx, cancle := context.WithCancel(context.Background())

    cli2 := proto.NewPingServiceClient(conn)
    ctx, cancle := context.WithCancel(context.Background())
    defer cancle()

    go xintiao(ctx, cli2)

    input := bufio.NewScanner(os.Stdin)
    liaotian(ctx, cli1, input)

}

func liaotian(ctx context.Context, cli proto.MessageServiceClient, input *bufio.Scanner) {
    for {
        fmt.Printf("输入消息：")
        if !input.Scan() {
            return
        }
        //fmt.Printf("输入的内容：%s\r\n", input.Text())
        resp, err := cli.Message(ctx, &proto.MessageRequest{
            Id:  1002,
            Msg: input.Text(),
        })
        if err != nil {
            fmt.Printf("Client send message error : %s\r\n", err.Error())
            return
        } else {
            fmt.Printf("客户端收到来自 %d 的消息：'%s'，code=%d.\r\n", resp.GetId(), resp.GetMsg(), resp.GetCode())
        }
    }
}

func xintiao(ctx context.Context, cli proto.PingServiceClient) {
    timer := time.NewTimer(5 * time.Second)
    for {
        <-timer.C // 定时发心跳
        _, err := cli.Ping(ctx, &proto.PingRequest{})
        if err != nil {
            fmt.Printf("接收出错 : %s\r\n", err.Error())
            return
        } else {
            fmt.Println("客户端收到心跳")
        }
        timer.Reset(5 * time.Second)
    }
}
